package codegen.builders;

import java.io.BufferedWriter;
import java.io.IOException;

import uk.co.q3c.deplan.client.util.Q3StringUtil;

public class CodegenField implements Comparable<CodegenField> {

	private Class<?> clazz;
	private String name;
	private Visibility visibility = Visibility.PRIVATE;
	private CodegenType parent;

	public CodegenField(CodegenType parent, String name, Class<?> clazz) {
		super();
		this.name = name;
		this.clazz = clazz;
		this.parent = parent;
	}

	public Class<?> getClazz() {
		return clazz;
	}

	public void setClazz(Class<?> clazz) {
		this.clazz = clazz;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Visibility getVisibility() {
		return visibility;
	}

	public CodegenField visibility(Visibility visibility) {
		this.visibility = visibility;
		return this;
	}

	public CodegenField getter(boolean usesGetter) {
		String methodName = Q3StringUtil.methodNamefromfieldName("get", name);
		if (usesGetter) {
			parent.addMethod(methodName)
					.returns(clazz)
					.addBodyLine("return " + name)
					.visibility(Visibility.PUBLIC);
		} else {
			parent.removeMethod(methodName);
		}
		return this;
	}

	public void write(BufferedWriter fw) throws IOException {
		fw.write(visibility.getText() + " " + clazz.getSimpleName() + " " + name);
	}

	@Override
	public int compareTo(CodegenField other) {
		return this.getName()
				.compareTo(other.getName());
	}

	public CodegenField setter(boolean usesSetter) {
		String methodName = Q3StringUtil.methodNamefromfieldName("set", name);
		if (usesSetter) {
			parent.addMethod(methodName)
					.addParameter(clazz, name)
					.addBodyLine("this." + name + " = " + name)
					.visibility(Visibility.PUBLIC);
		} else {
			parent.removeMethod(methodName);
		}
		return this;
	}

	public CodegenType getParent() {
		return parent;
	}

	public void setParent(CodegenType parent) {
		this.parent = parent;
	}

}
